package com.nenglai.admin.config;

import com.nenglai.common.captcha.CaptchaHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Map;


/**
 * 验证码配置
 *
 * @author kongdehui
 * @date 2021/04/24 14:48
 **/
@Configuration
@Slf4j
@ImportResource(locations = {"classpath:kaptcha.xml"})
public class CaptchaConfig {

    @Bean("login")
    public CaptchaHelper loginCaptchaHelper() {
        return new CaptchaHelper();
    }

    @Primary
    @Bean("sms")
    public CaptchaHelper smsCaptchaHelper() {
        return new CaptchaHelper();
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void clearExpired() {
        CaptchaHelper captchaHelper = loginCaptchaHelper();
        Map<String, CaptchaHelper.Element> captchaContainer = captchaHelper.getCaptchaContainer();
        captchaContainer.forEach((k, v) -> {
            if (v.expired()) {
                captchaContainer.remove(k);
                log.info("login captcha is expired, key = {}, value = {}", k, v.getValue());
            }
        });
    }
}
